package com.suke.czx.modules.express.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.suke.czx.common.annotation.SysLog;
import com.suke.czx.common.base.AbstractController;
import com.suke.czx.common.utils.CodeConstant;
import com.suke.czx.common.utils.FieldConstant;
import com.suke.czx.common.utils.ParamValidateUtil;
import com.suke.czx.common.utils.R;
import com.suke.czx.common.validate.ExpressSaveGroup;
import com.suke.czx.common.validate.ExpressUpdateGroup;
import com.suke.czx.modules.express.entity.Express;
import com.suke.czx.modules.express.service.ExpressService;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * 应用模块名称: 快递
 * 代码描述: 快递控制层
 * copyright: AUZAR ALL RIGHTS RESERVED
 * company: AUZAR
 *
 * @author: 颜米晨
 * @date: 2021/09/01 17:09:25
 */
@Validated
@RestController
@RequestMapping("/api/express")
@AllArgsConstructor
@Api(value = "ExpressController", tags = "快递管理")
public class ExpressController extends AbstractController {

    private final ExpressService expressService;

    /**
     * 分页查询快递列表
     * @param params 查询参数
     * @return VO
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:express:list')")
    public R list(@RequestParam Map<String, Object> params) {
        if (StrUtil.isBlankIfStr(params.get(FieldConstant.PAGE)) || StrUtil.isBlankIfStr(FieldConstant.LIMIT)) {
            return R.error("缺少分页信息");
        }
        // 查询列表数据
        QueryWrapper<Express> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(FieldConstant.DEL_FLG, CodeConstant.NOT_DEL);
        if (params.size() > 2){
            queryWrapper.like(!StrUtil.isBlankIfStr(params.get(FieldConstant.SENDER)), FieldConstant.SENDER, params.get(FieldConstant.SENDER))
                    .like(!StrUtil.isBlankIfStr(params.get(FieldConstant.RECEIVER)), FieldConstant.RECEIVER, params.get(FieldConstant.RECEIVER))
                    .like(!StrUtil.isBlankIfStr(params.get(FieldConstant.SIGNER)), FieldConstant.SIGNER, params.get(FieldConstant.SIGNER))
                    .like(!StrUtil.isBlankIfStr(params.get(FieldConstant.TRACKING_CONTENT)), StrUtil.toUnderlineCase(FieldConstant.TRACKING_CONTENT), params.get(FieldConstant.TRACKING_CONTENT))
                    .between(!StrUtil.isBlankIfStr(params.get(FieldConstant.SEND_BEGIN_DATE)) && !StrUtil.isBlankIfStr(params.get(FieldConstant.SEND_END_DATE)),
                            StrUtil.toUnderlineCase(FieldConstant.SEND_DATE), params.get(FieldConstant.SEND_BEGIN_DATE), params.get(FieldConstant.SEND_END_DATE))
                    .between(!StrUtil.isBlankIfStr(params.get(FieldConstant.RECEIVE_BEGIN_DATE)) && !StrUtil.isBlankIfStr(params.get(FieldConstant.RECEIVE_END_DATE)),
                            StrUtil.toUnderlineCase(FieldConstant.RECEIVE_DATE), params.get(FieldConstant.RECEIVE_BEGIN_DATE), params.get(FieldConstant.RECEIVE_END_DATE));
        }
        IPage<Express> expressPage = expressService.page(mpPageConvert.pageParamConvert(params), queryWrapper);
        return Objects.requireNonNull(R.ok().put(FieldConstant.TOTAL, expressPage.getTotal())).setData(Optional.ofNullable(expressPage.getRecords()).orElse(Lists.newArrayList()));
    }

    /**
     * 获取快递详情
     * @param expressId 快递id
     * @return VO
     */
    @RequestMapping(value = "/info/{expressId}", method = RequestMethod.GET)
    @PreAuthorize("hasRole('but:express:info')")
    public R info(@PathVariable("expressId") Long expressId) {
        Express express = expressService.getById(expressId);
        return R.ok().setData(express);
    }

    /**
     * 保存快递
     * @param express 联系人
     * @param bindingResult bindingResult
     * @return VO
     */
    @SysLog("保存快递")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:express:save')")
    public R save(@Validated(ExpressSaveGroup.class) Express express, BindingResult bindingResult) {
        // 入参校验结果
        if (bindingResult.hasErrors()) {
            return R.error(ParamValidateUtil.paramVilated(bindingResult));
        }
        express.setCreator(getUserId());
        express.setCreateTime(new Date());
        expressService.save(express);
        return R.ok();
    }

    /**
     * 更新快递
     * @param express 快递
     * @param bindingResult bindingResult
     * @return VO
     */
    @SysLog("更新快递")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:express:update')")
    public R update(@Validated(ExpressUpdateGroup.class) Express express, BindingResult bindingResult) {
        // 入参校验结果
        if (bindingResult.hasErrors()) {
            return R.error(ParamValidateUtil.paramVilated(bindingResult));
        }
        express.setUpdater(getUserId());
        express.setUpdateTime(new Date());
        expressService.updateById(express);
        return R.ok();
    }

    /**
     * 删除快递
     * @param expressId 快递编码
     * @return VO
     */
    @SysLog("删除快递")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:express:delete')")
    public R delete(@NotNull(message = "快递编码不能为空") Long expressId) {
        return expressService.updateDelExpress(expressId, getUserId());
    }

}
